import { defineComponent, ComputedRef, ref, onMounted, onUnmounted, computed } from 'vue';
import TopBar from './topbar';
import AudioStyle from './audioStyle';
import { Toast, Button, Icon } from 'vant';
import Styles from './correctionRemark.module.scss';
import { usePrepareStore } from '@/domain/correction/hooks/prepare';
import { useHomeWorksStore } from '@/domain/correction/hooks/homeWork';
import { ESubmitType } from '@/domain/correction/types/jobs/homeWork';
import { PreWorkTemplates } from '@/domain/correction/types/prepare';
import { ConsoleLogger } from '@/utils/debug-log';
import { router } from '../../router/index';
import { useCurrectStdStore } from '@/domain/correction/hooks/currectStd';
import { ReqJobCorrectParam, ReqRevisalParam } from '@/domain/correction/types/jobs/jobCorrect';
export default defineComponent({
  name: 'CorrectionRemark',
  setup() {
    const store = usePrepareStore();
    const homestore = useHomeWorksStore();
    const currectStore = useCurrectStdStore();
    const score = ref();
    const all_score = ref();
    const gold_num = ref();
    // const all_gold_num = ref();
    onMounted(() => {
      score.value = getScore();
      all_score.value = getAllScore();
      gold_num.value = getGoldNum();
      // all_gold_num.value = getAllGoldNum();
    });
    const getScore = () => {
      let n = 0;
      if (currectStore.state.submitType === ESubmitType.frist) {
        currectStore.state.reqJobCorrectParam?.correct_infos?.map((item) => {
          item.test_infos?.map((sitem) => {
            n += sitem.stu_score || 0;
          });
        });
      } else {
        currectStore.state.currentStdHomeWork?.correct?.details.map((item) => {
          item.scores?.map((sitem) => {
            n += sitem.stu_score || 0;
          });
        });
      }
      return n;
    };
    const getAllScore = () => {
      if (currectStore.state.currentStdHomeWork?.object?.object_score) {
        return score.value + currectStore.state.currentStdHomeWork?.object?.object_score;
      } else {
        return score.value;
      }
    };
    const getGoldNum = () => {
      return Math.floor(score.value * Number(currectStore.state.currentStdHomeWork?.factor));
    };
    const getAllGoldNum = () => {
      let n = gold_num.value;
      if (currectStore.state.currentStdHomeWork?.gold_num) {
        n += currectStore.state.currentStdHomeWork?.gold_num;
      }
      return n;
    };
    const template = computed(() => {
      return store.state.prepare?.pre_work.templates;
    });
    const stuTem: ComputedRef<Array<PreWorkTemplates | undefined>> = computed(() => {
      let arr = template.value?.filter((item) => {
        if (item.min_score <= all_score.value && item.max_score >= all_score.value) {
          return item;
        }
      });
      return arr || [];
    });
    const commit = async () => {
      let res = null;
      if (currectStore.state.submitType === ESubmitType.frist) {
        currectStore.state.reqJobCorrectParam!.gold_num = gold_num.value;
        currectStore.state.reqJobCorrectParam!.score = all_score.value;
        currectStore.state.reqJobCorrectParam!.comments = stuTem.value[0]?.content;
        currectStore.state.reqJobCorrectParam!.audio_url = stuTem.value[0]?.audio_url;
        res = await homestore.toCorrectSave(currectStore.state.reqJobCorrectParam as ReqJobCorrectParam);
      } else {
        res = await homestore.toCorrectRevise(currectStore.state.reqRevisalParam as ReqRevisalParam);
      }
      /*
        当前学生批改成功
        1、先把当前学生correctComplete置为true,表示已批改成功
        2、判断是否有其他学生未批改(correctComplete = false)，如果有，则自动进入其他学生的批改
        3、如果其他学生都批改成功，则自动请求接口，看是否还有最新学生提交
        4、如果最新学生有待批改的，则自动进入批改，反之跳讲次列表
      */
      if (res.code === 0) {
        Toast.success('提交成功');
        homestore.state.nCList &&
          homestore.state.nCList.map((item) => {
            if (item.stu_id === currectStore.state.currentStdHomeWork!.stu_id) {
              item.correctComplete = true;
            }
          });
        let item =
          homestore.state.nCList &&
          homestore.state.nCList.filter((item) => {
            if (!item.correctComplete) {
              return item;
            }
          });
        if (item && item.length > 0) {
          currectStore.selectStudent(item[0], homestore.state.homeWorkList?.homework!);
          window.location.reload();
        } else {
          // 重新请求，有则跳新的
          let data = await homestore.init();
          if (homestore.state.nCList && homestore.state.nCList.length > 0) {
            currectStore.selectStudent(homestore.state.nCList[0], homestore.state.homeWorkList?.homework!);
            window.location.reload();
          } else {
            // 没有则跳讲次列表
            router.push({
              path: '/planList',
              query: { class_id: JSON.parse(window.localStorage.getItem('routerParams') || '').class_id, course_id: window.localStorage.getItem('course_id') },
              replace: false
            });
          }
        }
      } else {
        Toast.fail(res.msg || '提交失败，请重试');
      }
    };
    return () => (
      <div>
        <TopBar bgColor="#FFF" stuName={currectStore.state.currentStdHomeWork?.stu_name || currectStore.state.currentStdHomeWork?.stu_id + ''}></TopBar>
        <div class={Styles['correction-remark']}>
          <div class={Styles['receive']}>
            <p class={Styles['item']}>
              <p class={Styles['item-num']}>
                <p class={Styles['item-label']}>总分</p>
                <p class={Styles['item-score']}>
                  <span class={Styles['score']}>{all_score.value}</span>
                  <span class={Styles['score-fen']}>分</span>
                </p>
              </p>
              <img class={Styles['img-num']} src="https://editor.xesimg.com/tailor/resource/grade-1658201899677.png"></img>
            </p>
            <p class={Styles['item']}>
              <p class={Styles['item-num']}>
                <p class={Styles['item-label']}>金币</p>
                <p class={Styles['item-score']}>
                  <span class={Styles['score']}>{gold_num.value}</span>
                  <span class={Styles['score-fen']}>个</span>
                </p>
              </p>
              <img class={Styles['img-num']} src="https://editor.xesimg.com/tailor/resource/gold-1658201899676.png"></img>
            </p>
          </div>
          <div class={Styles['synthesize']}>
            综合评语：
            <span class={Styles['synthesize-text']}>已添加 1 条评语</span>
            {/* <AudioStyle></AudioStyle> */}
          </div>
          <div class={Styles['remark']}>
            <span class={Styles['text']}>{stuTem.value[0]?.content}</span>
          </div>
          <div class={Styles['cor-btn']}>
            <Button
              class={Styles['btn']}
              round
              type="primary"
              onClick={() => {
                commit();
              }}
            >
              <Icon class={Styles['icon']} name="success" />
              提交批改
            </Button>
          </div>
        </div>
      </div>
    );
  }
});
